import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/modules/user'
import { ElMessage } from 'element-plus'

const routes = [
  {
    path: '/',
    redirect: '/admin/goods'
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/login/MyLogin.vue'),
    meta: {
      title: '登录',
      requiresAuth: false
    }
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('@/views/login/Register.vue'),
    meta: {
      title: '注册',
      requiresAuth: false
    }
  },
  {
    path: '/admin',
    name: 'Admin',
    component: () => import('@/views/admin/AdminLayout.vue'),
    meta: {
      requiresAuth: true
    },
    redirect: '/admin/goods',
    children: [
      {
        path: 'goods',
        name: 'GoodsManagement',
        component: () => import('@/views/admin/GoodsManagement.vue'),
        meta: {
          title: '商品管理'
        }
      },
      {
        path: 'chat',
        name: 'ChatManagement',
        component: () => import('@/views/admin/ChatManagement.vue'),
        meta: {
          title: '聊天管理'
        }
      },
      {
        path: 'hot-services',
        name: 'HotServicesManagement',
        component: () => import('@/views/admin/HotServicesManagement.vue'),
        meta: {
          title: '热门服务管理'
        }
      },
      {
        path: 'order',
        name: 'OrderManagement',
        component: () => import('@/views/admin/OrderManagement.vue'),
        meta: {
          title: '订单管理'
        }
      },
      {
        path: 'address',
        name: 'AddressManagement',
        component: () => import('@/views/admin/AddressManagement.vue'),
        meta: {
          title: '地址管理'
        }
      },
      {
        path: 'shopCar',
        name: 'ShopCarManagement',
        component: () => import('@/views/admin/ShopCarManagement.vue'),
        meta: {
          title: '购物车管理'
        }
      },
      {
        path: 'user-center',
        name: 'UserCenter',
        component: () => import('@/views/admin/UserCenter.vue'),
        meta: {
          title: '个人中心'
        }
      }
    ]
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'notfound',
    component: () => import('@/views/notFound.vue'),
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes,
  scrollBehavior() {
    return {
      top: 0,
      left: 0,
      behavior: 'smooth'
    }
  }
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  const userStore = useUserStore()
  if (to.meta.requiresAuth && !userStore.token) {
    ElMessage.warning('请先登录')
    next('/login')
  } else if (to.path === '/login' && userStore.token) {
    next('/admin/goods')
  } else {
    next()
  }
})

export default router
